package com.zjitc.controller;


import com.zjitc.pojo.*;
import com.zjitc.service.CategoryService;
import com.zjitc.utils.Utils;
import com.zjitc.vo.PageModel;
import com.zjitc.common.ServerResponse;
import com.zjitc.service.OrderService;
import com.zjitc.service.ProductService;
import com.zjitc.service.UserService;

import java.io.File;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * Create By IntelliJ IDEA
 *
 * @author: myq
 * @create-Time: 2017/12/19  11:48
 */
@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private UserService userService;
    @Autowired
    private ProductService productService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private CategoryService categoryService;

    private static final int COUNT = 10;
    private static final String ADMIN = "admin";
    private static String PAGE = "page";
    private static String USER = "user";
    private static String PRODUCT = "product";
    private static String CATEGORY = "list";
    private static String IS_HOT = "isHot";

    private static Logger logger = Logger.getLogger("log");

    @RequestMapping("gotoAdminLogin")
    public String gotoAdminLogin() {
        return "admin/index";
    }

    @RequestMapping(value = "/gohome", method = RequestMethod.POST)
    public String adminLogin(String username, String password, HttpSession session,
                             RedirectAttributes attributes)
            throws ServletException, IOException, NoSuchAlgorithmException {
        User user = userService.adminLogin(username, password);
        if (user != null) {
            session.setAttribute(ADMIN, user);
            return "/admin/home";
        }
        return "redirect:/index.do";
    }

    @RequestMapping("/adminOut")
    @ResponseBody
    public ServerResponse adminOut(HttpSession session)
            throws IOException, ServletException {
        session.removeAttribute(ADMIN);
        return ServerResponse.createSuccess();
    }

    //user
    @RequestMapping("/adminFindAllUser")
    public ModelAndView userAdminFindAll(
            HttpSession session,
            @RequestParam(value = "page", required = false, defaultValue = "0") String pageid)
            throws ServletException, IOException {
        ModelAndView modelAndView = new ModelAndView();
        if (session.getAttribute(ADMIN) != null) {
            PageModel<User> pageModel = userService.findall(Integer.parseInt(pageid), COUNT);
            modelAndView.addObject(PAGE, pageModel);
            modelAndView.setViewName("/admin/user/list");
        } else {
            modelAndView.setViewName("admin/index");
        }
        return modelAndView;
    }

    @RequestMapping("/userGoEdit")
    public ModelAndView goEdit(
            HttpSession session,
            @RequestParam("uid") String uid,
            @RequestParam(value = "page", required = false, defaultValue = "0") String page)
            throws ServletException, IOException {
        ModelAndView modelAndView = new ModelAndView("/admin/user/edit");
        if (session.getAttribute(ADMIN) != null) {
            User user = userService.findbyuid(uid);
            modelAndView.addObject(USER, user);
            modelAndView.addObject(PAGE, page);
        } else {
            modelAndView.setViewName("admin/index");
        }
        return modelAndView;
    }

    @RequestMapping("/adminUpdate")
    public String userAdminUpdate(User user, HttpSession session)
            throws IOException, NoSuchAlgorithmException, ServletException {
        if (session.getAttribute(ADMIN) != null) {
            userService.update(user);
            return "redirect:/admin/adminFindAllUser.do?page=0";
        } else {
            return "admin/index";
        }
    }

    @RequestMapping("/adminDeleteUser")
    public String userAdminDelete(String uid, HttpSession session)
            throws IOException, ServletException {
        if (session.getAttribute(ADMIN) != null) {
            userService.deluser(uid);
            return "redirect:/admin/adminFindAllUser.do?page=0";
        } else {
            return "admin/index";
        }
    }

    //product
    @RequestMapping("/adminFindAllProduct")
    public ModelAndView productAdminFindAll(
            HttpSession session,
            @RequestParam(value = "page", required = false, defaultValue = "0") String pageid)
            throws ServletException, IOException {
        ModelAndView m = new ModelAndView("/admin/product/list");
        if (session.getAttribute(ADMIN) != null) {
            PageModel<Product> page = productService.findAllProduct(Integer.parseInt(pageid), COUNT);
            m.addObject(PAGE, page);
        } else {
            m.setViewName("admin/index");
        }
        return m;
    }

    @RequestMapping("/productGoEdit")
    public ModelAndView productGoEdit(
            HttpSession session,
            String pid,
            @RequestParam(value = "pageid", required = false, defaultValue = "0") String pageid)
            throws ServletException, IOException {
        ModelAndView m = new ModelAndView("/admin/product/edit");
        if (session.getAttribute(ADMIN) != null) {
            Product product = productService.findbyid(pid);
            List<Category> list = categoryService.adminfindAll();
            Map<String, String> map = new HashMap<>();
            list.forEach(item -> {
                map.put(item.getCid(), item.getCname());
            });
            Map<Integer, String> ishot = new HashMap<>();
            ishot.put(0, "否");
            ishot.put(1, "是");
            m.addObject(IS_HOT, ishot);

            m.addObject(PRODUCT, product);
            m.addObject(CATEGORY, map);
            //同名 所以使用
            m.addObject(PAGE, pageid);
        } else {
            m.setViewName("admin/index");
        }
        return m;
    }

    @RequestMapping("/productGoAdd")
    public ModelAndView priductGoAdd(HttpSession session)
            throws ServletException, IOException {
        ModelAndView modelAndView = new ModelAndView("/admin/product/add");
        if (session.getAttribute(ADMIN) != null) {
            List<Category> list = categoryService.adminfindAll();
            modelAndView.addObject("list", list);
        } else {
            modelAndView.setViewName("admin/index");
        }
        return modelAndView;
    }

    @RequestMapping("/adminProductUpdate")
    @ResponseBody
    public ServerResponse adminProductUpdate(
            Product product, HttpServletRequest request, HttpServletResponse response, HttpSession session)
            throws IOException {
        if (session.getAttribute(ADMIN) != null) {
            Date date = new Date();
            System.out.println(product);
            product.setDate(date);
            if (!"".equals(product.getImage())) {
                String[] split = product.getImage().split("\\\\");
                product.setImage("products/1/" + split[2]);
            } else {
                product.setImage(null);
            }
            int update = productService.updateProduct(product);
            if (update == 1) {
                return ServerResponse.createSuccess();
            }
            return ServerResponse.createError();
        } else {
            return ServerResponse.createError();
        }
    }

    @RequestMapping(value = "/adminProductAdd", method = RequestMethod.POST)
    public String adminProductAdd(
            HttpSession session,
            HttpServletRequest request,
            Product product,
            @RequestParam("upload") MultipartFile file
    )
            throws ServletException, IOException {
        if (session.getAttribute(ADMIN) != null) {
            if (!file.isEmpty()) {
                product = savefile(product, request, file);
                productService.addproduct(product);
                return "redirect:/admin/adminFindAllProduct.do?page=0";
            }
            return "redirect:/admin/productGoAdd.do";
        } else {
            return "admin/index";
        }
    }

    private Product savefile(Product product, HttpServletRequest request, MultipartFile multipartFile) {
        String savedir = "products/1";
        String path = request.getServletContext().getRealPath("/" + savedir);
        String filename = multipartFile.getOriginalFilename();
        File filepath = new File(path, filename);
        if (!filepath.getParentFile().exists()) {
            filepath.getParentFile().mkdir();
        }
        try {
            multipartFile.transferTo(new File(path + File.separator + filename));
        } catch (IOException e) {
            e.printStackTrace();
        }

        product.setImage(savedir + "/" + filename);
        return product;
    }

    @RequestMapping("adminDeleteProduct")
    public String adminProductDelete(String pid, HttpSession session)
            throws ServletException, IOException {
        if (session.getAttribute(ADMIN) != null) {
            productService.deleteByPid(pid);
            return "redirect:/admin/adminFindAllProduct.do";
        } else {
            return "admin/index";
        }
    }

    //------------------------------------库存--------------------------------------------------------------
    @RequestMapping("adminCheckInventory")
    public ModelAndView adminCheckInventory(
            @RequestParam(value = "page", required = false, defaultValue = "0") String pageid,
            HttpSession session) {
        ModelAndView modelAndView = new ModelAndView("/admin/product/inventory");
        if (session.getAttribute(ADMIN) != null) {
            PageModel<Product> page = productService.findAllProduct(Integer.parseInt(pageid), COUNT);
            modelAndView.addObject("page", page);
        } else {
            modelAndView.setViewName("admin/index");
        }
        return modelAndView;
    }

    @RequestMapping("adminUpdateInventory")
    @ResponseBody
    public ServerResponse adminUpdateInventory(
            @RequestParam("pid") String pid,
            HttpSession session,
            @RequestParam("inventory") String count) {
        if (session.getAttribute(ADMIN) != null) {
            int update = productService.updateInventory(pid, Integer.parseInt(count));
            return ServerResponse.createSuccess(String.valueOf(update));
        } else {
            return ServerResponse.createError();
        }
    }

    //order
    @RequestMapping("adminFindAllOrder")
    public ModelAndView adminFindAllOrder(
            HttpSession session,
            @RequestParam(value = "page", required = false, defaultValue = "1") Integer pageid)
            throws ServletException, IOException {
        ModelAndView modelAndView = new ModelAndView("/admin/order/list");
        if (session.getAttribute(ADMIN) != null) {
            PageModel<Orders> page = orderService.findAllOrder(pageid, COUNT);
            modelAndView.addObject("page", page);
        } else {
            modelAndView.setViewName("admin/index");
        }
        return modelAndView;
    }

    @RequestMapping("adminFindItem")
    public ModelAndView adminFindItem(String oid, HttpSession session)
            throws ServletException, IOException {
        ModelAndView modelAndView = new ModelAndView("/admin/order/orderitem");
        if (session.getAttribute(ADMIN) != null) {
            User user = (User) session.getAttribute(USER);
            Orders order = orderService.findOrderFromRedis(user.getUid(), oid);
            modelAndView.addObject("order", order);
        } else {
            modelAndView.setViewName("admin/index");
        }
        return modelAndView;
    }


    //category
    @RequestMapping("adminFindAllCategory")
    public ModelAndView categoryAdminFindAll(HttpSession session)
            throws ServletException, IOException {
        ModelAndView modelAndView = new ModelAndView("/admin/category/list");
        if (session.getAttribute(ADMIN) != null) {
            List<Category> list = categoryService.adminfindAll();
            modelAndView.addObject("list", list);
        } else {
            modelAndView.setViewName("admin/index");
        }
        return modelAndView;
    }

    @RequestMapping("goCategoryEdit")
    public ModelAndView goCategoryEdit(Category category, HttpSession session) {
        ModelAndView modelAndView = new ModelAndView("/admin/category/edit");
        if (session.getAttribute(ADMIN) != null) {
            String cname = "cname";
            String item2 = "cid";
            modelAndView.addObject(cname, category.getCname());
            modelAndView.addObject(item2, category.getCid());
        } else {
            modelAndView.setViewName("admin/index");
        }
        return modelAndView;
    }

    @RequestMapping("goAddCategory")
    public String goAddCategory(HttpSession session) {
        if(session.getAttribute(ADMIN) != null) {
            return "/admin/category/add";
        }else {
            return "admin/index";
        }
    }

    @RequestMapping("addCategory")
    public String addCategory(Category category,HttpSession session)
            throws ServletException, IOException {
        if(session.getAttribute(ADMIN) != null) {
            List<Category> allcate = categoryService.adminfindAll();
            int count = allcate.size();
            String cid = String.valueOf(count + 1);
            category.setCid(cid);
            int cou = categoryService.add(category);
            return "redirect:/admin/adminFindAllCategory.do";
        }else {
            return "admin/index";
        }
    }

    @RequestMapping("adminCategoryUpdate")
    public String adminCategoryUpdate(Category category,HttpSession session)
            throws ServletException, IOException {
        if(session.getAttribute(ADMIN) != null){
            categoryService.update(category);
            return "redirect:/admin/adminFindAllCategory.do";
        }else {
            return "admin/index";
        }
    }

    @RequestMapping("adminCategoryDelete")
    public String adminCategoryDelete(String cid,HttpSession session)
            throws ServletException, IOException {
        if (session.getAttribute(ADMIN) != null) {
            categoryService.deletebycid(cid);
            return "redirect:/admin/adminFindAllCategory.do";
        }else {
            return "admin/index";
        }
    }
}
